package org.example.topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Random;

public class TopicsProducer {


    public static final String TOPIC_EXCHANGE = "topics";


    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            //声明广播类型的交换机
            channel.exchangeDeclare(TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC);
            //声明一个交换机
            String routingKey = getRoutingKey(args);
            String randomMessage = new Random(10).nextInt() + "";
            channel.basicPublish(TOPIC_EXCHANGE, routingKey, null, ("消息" + randomMessage).getBytes());
            // In the Java client, when we supply no parameters to queueDeclare() we
            // create a non-durable, exclusive, autodelete queue with a generated name:
            // AMQP.Queue.DeclareOk declareOk = channel.queueDeclare();
            // 获取一个非持久化，排他，自动删除的队列
            // String queueName = declareOk.getQueue();
            // channel.queueBind(queueName,PUB_EXCHANGE,"");
        }
    }

    private static String getRoutingKey(String[] args) {
        if (args.length < 1)
            return "anonymous.info";
        return args[0];
    }
}
